package com.sxf.rental.controller;


import cn.hutool.core.convert.NumberWithFormat;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTPayload;
import com.sxf.rental.entity.Permission;
import com.sxf.rental.entity.User;
import com.sxf.rental.security.CustomerAuthenticationException;
import com.sxf.rental.service.IUserService;
import com.sxf.rental.utils.JwtUtils;
import com.sxf.rental.utils.RedisUtils;
import com.sxf.rental.utils.Result;
import com.sxf.rental.utils.RouteTreeUtils;
import com.sxf.rental.vo.RouteVo;
import com.sxf.rental.vo.TokenVo;
import com.sxf.rental.vo.UserInfoVo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RequestMapping("/rental/auth/")
@RestController
public class AuthController {
    @Resource
    private RedisUtils redisUtils;

    @Resource
    private IUserService userService;

    @PostMapping("/refreshToken")
    public Result refreshToken(HttpServletRequest request){
        String token = request.getHeader("token");
        if (StrUtil.isEmpty(token)){
            token= request.getParameter("token");
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails userDetails =(UserDetails) authentication.getPrincipal();
        //从Token里面获取用户名
        String username = JwtUtils.parseToken(token).getClaim("username").toString();
        String newToken="";
        if (StrUtil.equals(username,userDetails.getUsername())){
            Map<String,Object> map=new HashMap<>(){
                {
                    put("username",userDetails.getUsername());
                }
            };
            newToken = JwtUtils.createToken(map);
        }else {
            throw new CustomerAuthenticationException("token数据异常");
        }
        //获取本次Token过期时间
        NumberWithFormat claim=(NumberWithFormat)JwtUtils.parseToken(newToken).getClaim(JWTPayload.EXPIRES_AT);
        DateTime dateTime=(DateTime)claim.convert(DateTime.class,claim);
        long expireTime=dateTime.getTime();
        TokenVo tokenVo=new TokenVo();
        tokenVo.setToken(newToken).setExpireTime(expireTime);
        //清除原有Token
        redisUtils.del("token:"+token);
        //把Token存到Redis中,设置过期时间
        long nowTime= DateTime.now().getTime();
        redisUtils.set("token:"+newToken,newToken,(expireTime-nowTime)/1000);
        return Result.success(tokenVo).setMessage("刷新成功");
    }

    @GetMapping("/info")
    public Result getUserInfo(){
        //从securityContextHolder中获取用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication==null){
            return Result.fail().setMessage("认证信息为空");
        }
        User user=(User)authentication.getPrincipal();

        List<String> list = userService.selectRoleName(user.getId());
        Object[] array = list.toArray();
//        Object[] array = user.getPermissionList().stream().filter(Objects::nonNull).map(Permission::getPermissionCode).toArray();
        UserInfoVo userInfoVo=new UserInfoVo(user.getId(),user.getUsername(),
                user.getAvatar(), user.getNickname(),array);
        return Result.success(userInfoVo).setMessage("获取用户信息成功");
    }

    @GetMapping("/menuList")
    public Result getMenuList(){
        //获取用户当前信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication==null){
            return Result.fail().setMessage("认证信息为空");
        }
        User user=(User)authentication.getPrincipal();
        //获取用户权限列表
        List<Permission> permissionList=user.getPermissionList();
        //获取用户菜单
        //将Permission为2的按钮移除，不需要生成对应菜单
        permissionList.removeIf(permission -> Objects.equals(permission.getPermissionType(),2));
        List<RouteVo> routeVoList = RouteTreeUtils.buildRouteTree(permissionList, 0);
        return Result.success(routeVoList).setMessage("获取用户菜单成功");

    }
}
